package com.powermgr.boringtest.utils;

import com.powermgr.boringtest.bean.PrData;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Date;
import java.util.Properties;

import static com.powermgr.boringtest.utils.ConfigUtils.*;

/**
 * SendEmail
 *
 * @author qiuxiangdong
 * @date 2023/9/23 16:42
 */
@Log4j2
public class EmailUtils {
    public static void SendEmail(PrData prData, int code){
        log.info("*开始发送邮件");
        String myEmailAccount = InitUtils.getUserValue("email");
        String myEmailPassword = InitUtils.getUserValue("email_token");
        String myEmailSMTPHost = InitUtils.getUserValue("email_smtp");
        String receiveMailAccount = prData.getEmail();
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", myEmailSMTPHost);
        props.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(props);
        session.setDebug(false);
        try {
            MimeMessage message = createMessage(session, myEmailAccount, receiveMailAccount,prData,code);
            Transport transport = session.getTransport();
            transport.connect(myEmailAccount, myEmailPassword);
            if (message != null) {
                transport.sendMessage(message, message.getAllRecipients());
            }
            transport.close();
            log.info("*邮件发送成功");
        } catch (Exception e) {
            log.error("*邮件发送失败", e);
        }
    }
    private static MimeMessage createMessage(Session session, String sendMail, String receiveMail, PrData prData, int code) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sendMail, "BoringTest", "UTF-8"));
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));
        MimeBodyPart text = new MimeBodyPart();
        String title = null;
        String body = null;
        if (code == SUCCESS ){
            title = "BoringTest 报告: 【" + prData.getTitle() + "】";
            body = "Pr测试用例执行报告：<br>" +
                    "Pr链接为："+ prData.getPrUrl() + "<br>" +
                    "版本分支为："+ prData.getBranch() + "<br>" +
                    "测试类型为："+ prData.getType() + "<br>" +
                    "测试模块为："+ prData.getModule() + "<br>" +
                    "结果见附件~";
        }
        if (code == ROOT_FALSE ){
            title = "【刷机失败】 BoringTest 报告: 【" + prData.getTitle() + "】";
            body = "Test：<br>" +
                    "Brushing false,  please check the device." + "<br>" +
                    "刷机失败了，请联系相关人员检查。"+ "<br>" + "<br>" +
                    "Pr链接为："+ prData.getPrUrl() + "<br>" +
                    "版本分支为："+ prData.getBranch() + "<br>" +
                    "测试类型为："+ prData.getType() + "<br>" +
                    "测试模块为："+ prData.getModule() + "<br>" +
                    "~";
        }
        if (code == UN_TAR_GZ_FALSE ){
            title = "【文件解压失败】 BoringTest 报告: 【" + prData.getTitle() + "】";
            body = "Test：<br>" +
                    "文件解压失败，请联系相关人员检查。"+ "<br>" + "<br>" +
                    "Pr链接为："+ prData.getPrUrl() + "<br>" +
                    "版本分支为："+ prData.getBranch() + "<br>" +
                    "测试类型为："+ prData.getType() + "<br>" +
                    "测试模块为："+ prData.getModule() + "<br>" +
                    "~";
        }
        message.setSubject(title, "UTF-8");
        text.setContent(body,"text/html;charset=utf-8");
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(text);
        mimeMultipart.setSubType("related");
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mimeMultipart);
        FileUtils.copyDirectory(new File(SN + File.separator + prData.getSn_id() +  File.separator + "case"
                        + File.separator + "acts" + File.separator + "reports"),
                new File(SN + File.separator + prData.getSn_id() +  File.separator + "case"
                        + File.separator + "developertest" + File.separator + "reports"));
        FileUtils.copyDirectory(new File(SN + File.separator + prData.getSn_id() +  File.separator + "case"
                        + File.separator + "hats" + File.separator + "reports"),
                new File(SN + File.separator + prData.getSn_id() +  File.separator + "case"
                        + File.separator + "developertest" + File.separator + "reports"));
        String reportPath = SN + File.separator + prData.getSn_id() +  File.separator + "case"
                + File.separator + "developertest" + File.separator + "reports";
        log.info(reportPath);
        try{
            MimeMultipart allFile = new MimeMultipart();
            if (code == SUCCESS) {
                File f = new File(reportPath);
                File[] result = f.listFiles();
                int fileNums = 0;
                for (String module : prData.getModule()) {
                    for (String type: prData.getType()) {
                        assert result != null;
                        File fs = result[fileNums];
                        if (TypeUtils.IsBenchmark(type)){
                            File summary = new File(reportPath + File.separator + fs.getName() + File.separator + "benchmark" + File.separator + "benchmark" + File.separator + "report" + File.separator + "index.html");
                            if (summary.exists()) {
                                MimeBodyPart appendix = new MimeBodyPart();
                                appendix.setDataHandler(new DataHandler(new FileDataSource(summary)));
                                appendix.setFileName(fileNums + 1 + "." + type + "-" + module + ".html");
                                allFile.addBodyPart(appendix);
                            }
                        } else {
                            File summary = new File(reportPath + File.separator + fs.getName() + File.separator + "summary_report.html");
                            if (summary.exists()) {
                                MimeBodyPart appendix = new MimeBodyPart();
                                appendix.setDataHandler(new DataHandler(new FileDataSource(summary)));
                                appendix.setFileName(fileNums + 1 + "." + type + "-" + module + ".html");
                                allFile.addBodyPart(appendix);
                            }
                            File failures = new File(reportPath + File.separator + fs.getName() + File.separator + "failures_report.html");
                            if (failures.exists()) {
                                MimeBodyPart appendix = new MimeBodyPart();
                                appendix.setDataHandler(new DataHandler(new FileDataSource(failures)));
                                appendix.setFileName(fileNums + 1 + "."  + "Fail" + "-" + type + "-" + module + ".html");
                                allFile.addBodyPart(appendix);
                            }
                        }
                        fileNums++;
                    }
                }
            }
            allFile.addBodyPart(contentText);
            allFile.setSubType("mixed");
            message.setContent(allFile);
            message.saveChanges();
            message.setSentDate(new Date());
            message.saveChanges();
        }catch (Exception exception){
            return null;
        }
        return message;
    }
}
